/*
编写 : Hexh
时间 : 2012-11-27 14:38:42
*/
using System;
using System.ComponentModel;
using System.Web.Mvc;
using FSBS.Core.Entity;
using FSBS.Facade;
using HMIS.FrameWork;
using HMIS.Infrastructure.Core.Authority;
using HMIS.Infrastructure.Facade.Authority;
using HMIS.MVC.CommonSupport;
using HMIS.MVC.ViewModel;
using Iesi.Collections.Generic;
using System.Collections.Generic;
using HMIS.Infrastructure.Core.Entities;
using HMIS.Infrastructure.Facade;

namespace HMIS.MVC.Controllers
{
	/// <summary>
	///	 the mvc class of FsbsQmTrsf
	/// </summary>
	public class FsbsQmTrsfController : BaseController
	{

		private readonly IFsbsQmTrsfFacade FsbsQmTrsfFacade;
		private readonly IHospUserFacade HospUserFacade;
		private readonly IFsbsQmCrifFacade FsbsQmCarinfoFacade;
		private readonly IInfraApproveHisFacade InfraApproveHisFacade;
		private readonly IInfraApproveFacade InfraApproveFacade;

		public FsbsQmTrsfController(IFsbsQmTrsfFacade FsbsQmTrsfFacade,
			IFsbsQmCrifFacade FsbsQmCarinfoFacade,
			IHospUserFacade HospUserFacade,
			IInfraApproveHisFacade InfraApproveHisFacade,
			IInfraApproveFacade InfraApproveFacade)
		{
			this.FsbsQmTrsfFacade = FsbsQmTrsfFacade;
			this.HospUserFacade = HospUserFacade;
			this.FsbsQmCarinfoFacade = FsbsQmCarinfoFacade;
			this.InfraApproveHisFacade = InfraApproveHisFacade;
			this.InfraApproveFacade = InfraApproveFacade;
		}

		[ExtResult]
		[Description("添加修改FsbsQmTrsf信息")]
		public ActionResult SaveOrUpdate()
		{
			FsbsQmTrsf entity;
			if (String.IsNullOrEmpty(Request["Id"]))
			{
				entity = new FsbsQmTrsf
				{
					Trtype = Request["Trtype"],
					Opusid = Request["Opusid"],
					Otdpid = Request["Otdpid"],
					Indpid = Request["Indpid"],
					Exoutm = Request["Exoutm"] == null ? DateTime.MinValue : DateTime.Parse(Request["Exoutm"]),
					Exartm = Request["Exartm"] == null ? DateTime.MinValue : DateTime.Parse(Request["Exartm"]),
					Reason = Request["Reason"],
					Description = Request["Description"],
					Trstate = CarTransferState.Editing,
				};
			}
			else
			{
				// get the entity.
				entity = FsbsQmTrsfFacade.Get(Request["Id"]);
				// set new value..
				entity.Trtype = Request["Trtype"];
				entity.Opusid = Request["Opusid"];
				entity.Otdpid = Request["Otdpid"];
				entity.Indpid = Request["Indpid"];
				entity.Exoutm = Request["Exoutm"] == null ? DateTime.MinValue : DateTime.Parse(Request["Exoutm"]);
				entity.Exartm = Request["Exartm"] == null ? DateTime.MinValue : DateTime.Parse(Request["Exartm"]);
				entity.Reason = Request["Reason"];
				entity.Description = Request["Description"];
			}
			// 保存信息
			FsbsQmTrsfFacade.SaveOrUpdate(entity);

			return this.JsonFormat(new ExtResult { success = true, id = entity.Id });
		}

		[ExtResult]
		[Description("删除FsbsQmTrsf基本资料")]
		public ActionResult Delete()
		{
			FsbsQmTrsfFacade.Delete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("物理删除FsbsQmTrsf基本资料")]
		public ActionResult PhysicsDelete()
		{
			FsbsQmTrsfFacade.PhysicsDelete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("获取FsbsQmTrsf清单")]
		public ActionResult GetPlist()
		{
			long total;
			var data = FsbsQmTrsfFacade.GetPlist(
				Request["q_query"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			// 修改关联查询返回的类型
			return this.JsonFormat(
				new ExtGirdData<FsbsQmTrsf> { total = total, data = data },
				new string[] { "" });
		}

		[Description("获取调拨单车辆清单")]
		public ActionResult GetCarPList()
		{
			long total;
			var data = FsbsQmTrsfFacade.GetTrsfCarlist(
				Request["trsfid"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			return this.JsonFormat(
				new ExtGirdData<FsbsQmCrif> { total = total, data = data },
				new string[] { "" });
		}

		[ExtResult]
		[Description("汽贸-调拨单-添加车辆")]
		public ActionResult AddCars()
		{
			FsbsQmTrsf trEntity = FsbsQmTrsfFacade.Get(Request["trsfid"]);
			if (trEntity.Trstate != CarTransferState.Editing)
				throw new ValidationException("该调拨单状态不可修改.");

			FsbsQmCrif car_Entity;
			string[] Ids = Request["Ids"].Split(',');
			for (int i = 0; i < Ids.Length; i++)
			{
				if (!string.IsNullOrEmpty(Ids[i]))
				{
					car_Entity = FsbsQmCarinfoFacade.Get(Ids[i]);
					if (car_Entity.State != CarState.InStore)
						throw new ValidationException("车辆[" + car_Entity.Id + "]状态不在库存中，请检查.");

					if (!trEntity.Cars.Contains(car_Entity))
						trEntity.Cars.Add(car_Entity);
				}
			}

			FsbsQmTrsfFacade.SaveOrUpdate(trEntity);
			return this.JsonFormat(new ExtResult { success = true, id = trEntity.Id });
		}

		[ExtResult]
		[Description("汽贸-调拨单-删除车辆")]
		public ActionResult DeleteCars()
		{
			FsbsQmTrsf trEntity = FsbsQmTrsfFacade.Get(Request["trsfid"]);
			if (trEntity.Trstate != CarTransferState.Editing)
				throw new ValidationException("该调拨单状态不可修改.");

			FsbsQmCrif car_Entity = FsbsQmCarinfoFacade.Get(Request["Id"]);
			car_Entity.State = CarState.InStore;
			trEntity.Cars.Remove(car_Entity);
			FsbsQmTrsfFacade.SaveOrUpdate(trEntity);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("汽贸-调拨单-提交审批")]
		public ActionResult ToApproveProcess()
		{
			foreach (string id in Request["Ids"].Split(','))
			{
				FsbsQmTrsf entity = FsbsQmTrsfFacade.Get(id);
				if (entity.Trstate != CarTransferState.Editing)
					throw new ValidationException("错误:[" + entity.Id + "]的当前状态是[" + entity.Trstate + "].不允许提交审批。");

				InfraApproveHis apprInfo = InfraApproveHisFacade.CreateApproveHis(entity.Id, entity.ToSmsString(), "ap_" + entity.Trtype, entity.Otdpid);

				entity.ApprHisId = apprInfo.Id;
				entity.Trstate = CarTransferState.Appling;
				FsbsQmTrsfFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("汽贸-调拨单-审批")]
		public ActionResult Approve()
		{
			InfraApproveHisStep approveHisStep = this.InfraApproveFacade.ApproveProcess(
				Request["Id"],
				Request["InputUserLName"],
				Request["InputUserPwd"],
				Request["InputAprCode"],
				Convert.ToInt32(Request["InputApprState"])
				);
			// 审批通过
			FsbsQmTrsf trsfEntity = FsbsQmTrsfFacade.Get(approveHisStep.ApproveHis.ApproveItemId);
			if (approveHisStep.ApproveHis.ApproveState == 1)
				trsfEntity.Trstate = CarTransferState.Agreed;
			else if (approveHisStep.ApproveHis.ApproveState == -1)
				trsfEntity.Trstate = CarTransferState.Refused;
			else
				trsfEntity.Trstate = CarTransferState.Appling;
			FsbsQmTrsfFacade.SaveOrUpdate(trsfEntity);

			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("汽贸-调拨单-调出")]
		public ActionResult SendOut()
		{
			CurrentUser cUser = new CurrentUser();
			foreach (string id in Request["Ids"].Split(','))
			{
				FsbsQmTrsf entity = FsbsQmTrsfFacade.Get(id);
				if (entity.Trstate != CarTransferState.Agreed)
					throw new ValidationException("错误:-3001,商品车调派单[" + entity.Id + "]的当前状态是[" + entity.Trstate + "].不允许进行调出.");

				entity.Trstate = CarTransferState.Processing;
				entity.Oudpus = cUser.UserInfo.Id;
				entity.Acoutm = System.DateTime.Now;
				// 修改提出的车辆清单信息
				foreach (FsbsQmCrif cardetail in entity.Cars)
				{
					cardetail.State = CarState.InTransfer;
				}
				FsbsQmTrsfFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("汽贸-调拨单-接收")]
		public ActionResult Recive()
		{
			CurrentUser cUser = new CurrentUser();
			foreach (string id in Request["Ids"].Split(','))
			{
				FsbsQmTrsf entity = FsbsQmTrsfFacade.Get(id);
				if (entity.Trstate != CarTransferState.Processing)
					throw new ValidationException("错误:-3002,商品车调派单[" + entity.Id + "]的当前状态是[" + entity.Trstate + "].不允许接收.");

				entity.Trstate = CarTransferState.Returned;
				entity.Indpus = cUser.UserInfo.Id;
				entity.Acartm = System.DateTime.Now;
				// 修改提出的车辆清单信息
				foreach (FsbsQmCrif cardetail in entity.Cars)
				{
					cardetail.State = CarState.ToStore;
					cardetail.DepartmentId = entity.Indpid;
				}
				FsbsQmTrsfFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("汽贸-调拨单-入库")]
		public ActionResult StoreIn()
		{
			CurrentUser cUser = new CurrentUser();
			foreach (string id in Request["Ids"].Split(','))
			{
				FsbsQmTrsf entity = FsbsQmTrsfFacade.Get(id);
				if (entity.Trstate != CarTransferState.Returned)
					throw new ValidationException("错误:-3003,商品车调派单[" + entity.Id + "]的当前状态是[" + entity.Trstate + "].不允许入库.");

				entity.Trstate = CarTransferState.Stored;
				entity.Indpus = cUser.UserInfo.Id;
				// 修改提出的车辆清单信息
				foreach (FsbsQmCrif cardetail in entity.Cars)
				{
					cardetail.State = CarState.InStore;
					cardetail.DepartmentId = entity.Indpid;
				}
				FsbsQmTrsfFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[Description("汽贸-调拨单-获取调拨单信息")]
		public ActionResult GetById()
		{
			var entity = FsbsQmTrsfFacade.Get(Request["Id"]);
			return this.JsonFormat(
			   new ExtFormLoadData<FsbsQmTrsf> { data = new FsbsQmTrsf[] { entity } }, new string[] { "AuthorizeUsers" }
			   );
		}

		[ExtResult]
		[Description("汽贸-调拨单-判断字段是否唯一")]
		public ActionResult IsFieldExist()
		{
			var result = FsbsQmTrsfFacade.IsFieldExist(Request["FieldName"], Request[Request["FieldName"]], Request["Id"]);
			return this.JsonFormat(new ExtResult { success = !result, msg = "已存在相同的项!" });
		}

		[Description("汽贸-调拨单-返回商品车库存状态信息")]
		public ActionResult GetCarTransferState()
		{
			var result = EnumDescription.ToList<CarTransferState>();
			return this.JsonFormat(result);
		}
	}
}
